<template>
  <div class="common-wrapper">
    <div class="common-title">历史轨迹曲线</div>
    <div class="common-main">
      <el-form
        ref="search"
        class="common-search"
        :inline="true"
        :rules="searchRules"
        :model="search"
        :show-message="false"
      >
        <el-form-item>
          <el-select
            v-model="search.org"
            placeholder="选择组织"
            size="small"
            clearable
          >
            <el-option
              v-for="(item, index) in orgOption"
              :key="index"
              :label="item['key_value']"
              :value="item['key_value']"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="search.cj"
            placeholder="选择车间"
            size="small"
            clearable
          >
            <el-option
              v-for="(item, index) in cjOption"
              :key="index"
              :label="item['key_value']"
              :value="item['key_value']"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="search.gongxu"
            placeholder="选择工序"
            size="small"
            clearable
            @change="changeGX"
          >
            <el-option
              v-for="(item, index) in gxOption"
              :key="index"
              :label="item['key_value']"
              :value="item['key_value']"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="params">
          <el-cascader
            v-model="search.params"
            ref="cascader"
            placeholder="选择参数类型"
            size="small"
            :options="options"
            :props="cascaderProps"
            style="width: 240px"
            collapse-tags
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="search.devSn"
            placeholder="选择机台"
            size="small"
            multiple
            clearable
            class="mul-selection"
            popper-class="mul-select"
            collapse-tags
          >
            <el-option
              v-for="(item, index) in equipOption"
              :key="index"
              :label="search.gongxu + item.key_value + '号'"
              :value="item.key_value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="startTime">
          <el-date-picker
            size="small"
            v-model="time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            clearable
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item class="btn-list">
          <el-button type="primary" size="small" @click="searchNow"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="chart-tabs">
        <el-radio
          v-model="chartActive"
          size="samll"
          class="chart-radio"
          v-for="(item, index) in chartBtnArr"
          :label="item.value"
          :key="index"
          border
          @change="(e) => changeChartTabs(e, item, index)"
          >{{ item.label }}</el-radio
        >
      </div>
      <div class="chart" ref="chart" v-loading="loading"></div>
      <div class="chart-table" ref="chartTable">
        <el-table
          :data="tableData"
          style="width: 100%"
          :max-height="tableHeight"
        >
          <el-table-column label="序号" width="55" align="center">
            <template slot-scope="{ row, column, $index }">
              {{ parseInt($index) + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="org" label="组织" align="center" />
          <el-table-column prop="cj" label="车间" align="center" />
          <!-- <el-table-column prop="gongxu" label="工序" align="center" /> -->
          <el-table-column prop="devSn" label="设备编号" align="center" />
          <el-table-column
            prop="time"
            width="160"
            label="时间"
            align="center"
          />
          <el-table-column
            v-for="(item, index) in columns"
            :key="index"
            :label="item.label"
            align="center"
          >
            <template v-for="(column, i) in item.children">
              <el-table-column
                v-if="column.value == 'llxs'"
                :prop="column.value"
                :label="column.label"
                :key="i"
                align="center"
                width="100"
                :formatter="llxsFilter"
              />
              <el-table-column
                v-else
                :prop="column.value"
                :label="column.label"
                :key="i"
                align="center"
                width="100"
              />
            </template>
          </el-table-column>
          <el-table-column prop="bc" label="班次" align="center">
          </el-table-column>
        </el-table>
      </div>
      <div class="common-pagination">
        <el-pagination
          background
          layout="prev, pager, next, sizes, jumper"
          :page-size="search.pageSize"
          :current-page.sync="search.current"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getSysDict,
  getSysDictByName,
  getParams1,
  getParams2,
} from '@/api/common';
import { getHistoryTrackData } from '@/api/production';
export default {
  data() {
    return {
      tableHeight: 200,
      time: [],
      search: {
        startTime: '',
        cj: '五纺',
        endTime: '',
        gongxu: '',
        devSn: [],
        org: '恒源',
        params: [],
        size: 10,
        current: 1,
      },
      searchRules: {
        params: [
          { required: true, message: '请选择参数！', trigger: 'change' },
        ],
        devSn: [{ required: true, message: '请选择车台！', trigger: 'change' }],
        startTime: [
          { required: true, message: '请选择时间！', trigger: 'change' },
        ],
      },
      cascaderProps: {
        lazy: true,
        multiple: true,
        label: 'label',
        lazyLoad: async (node, resolve) => {
          if (node.level) {
            let form = {
              gongxu: node.data.gongxu,
              cs_type: node.data.cs_type,
            };
            const { data } = await getParams2(form);
            data.map((item) => {
              item.label = item['cs_name'];
              item.value = item['cs'];
              item.leaf = true;
            });
            resolve(data);
          }
        },
      },
      options: [],
      // 图表部分
      legend: [],
      series: [],
      yAxis: [],
      timeSource: [],
      total: 10,
      chartActive: '',
      chartBtnArr: [],
      myChart: null,
      loading: false,
      csOption: [],
      equipOption: [],
      tableData: [],
      columns: [],
    };
  },
  created() {
    window.addEventListener('resize', () => {
      this.getHeight();
      this.getChartData();
    });
  },
  mounted() {
    document.getElementsByClassName(
      'el-pagination__jump'
    )[0].childNodes[0].nodeValue = '跳至';
    this.$nextTick(() => {
      this.getHeight();
      // this.getChartData();
      this.getParams();
    });
  },
  destroyed() {
    window.removeEventListener('resize', this.getHeight, this.getChartData);
  },
  watch: {
    time: function (val) {
      if (val) {
        this.search.startTime = val[0];
        this.search.endTime = val[1];
      } else {
        this.search.startTime = '';
        this.search.endTime = '';
      }
    },
  },
  computed: {
    bcOption() {
      return this.$store.getters.bcOption;
    },
    orgOption() {
      return this.$store.getters.orgOption;
    },
    cjOption() {
      return this.$store.getters.cjOption;
    },
    gxOption() {
      return this.$store.getters.gxOption;
    },
  },
  methods: {
    // 下拉框部分
    async getParams(val) {
      const { data } = await getParams1({ gongxu: val });
      let arr = [];
      data.map((item) => {
        let obj = Object.assign({}, item);
        obj.label = item.cs_type;
        obj.value = item.cs_type;
        arr.push(obj);
      });
      this.options = arr;
    },
    async getEquip(val) {
      const equipData = await getSysDict(val);
      this.equipOption = equipData.data.dataList;
    },
    async getTableData() {
      let form = Object.assign({}, this.search);
      delete form['params'];
      const res = await getHistoryTrackData(form);
      if (res.code == 1) {
        this.tableData = res.data.records;
        this.total = res.data.total;
      }
    },
    async getChartData() {
      this.loading = true;
      this.chartActive = this.chartBtnArr[0]['value'];
      let form = Object.assign({}, this.search);
      delete form['params'];
      form.size = -1;
      const res = await getHistoryTrackData(form);
      if (res.code == 1) {
        const data = res.data.records;
        this.timeSource = [];
        this.yAxis = this.arrayGroupBy(data, 'devSn');
        this.series = [];
        this.legend = [];
        this.yAxis.map((devSn, devSnIndex) => {
          devSn.map((item, index) => {
            // 构建seires
            if (index == 0) {
              this.series.push({
                name: '车台' + item.devSn,
                type: 'line',
                symbol: 'circle',
                symbolSize: 8,
                itemStyle: {
                  borderWidth: 2,
                  borderColor: '#fff',
                },
                data: [],
              });
              this.legend.push('车台' + item.devSn);
            }
            // 获取对应项数据
            // 只取一次时间X轴
            if (devSnIndex == 0) {
              this.timeSource.push(item.time);
            }
            // 如果为llxs需单独处理
            if (this.chartActive == 'llxs') {
              let llxsVal = parseInt(item[this.chartActive]) / 100;
              this.series[devSnIndex]['data'].push(llxsVal);
            } else {
              this.series[devSnIndex]['data'].push(item[this.chartActive]);
            }
          });
        });
        let options = this.setOptions();
        this.chartInit(options);
      }
      this.loading = false;
    },
    chartInit(options) {
      if (this.myChart == null) {
        this.myChart = this.$echarts.init(this.$refs.chart);
      } else {
        this.myChart.clear();
        this.myChart = this.$echarts.init(this.$refs.chart);
      }
      this.myChart.setOption(options);
    },
    setOptions() {
      let option = {
        tooltip: {
          trigger: 'axis',
          textStyle: {
            fontSize: 13,
          },
          padding: 10,
          backgroundColor: 'rgba(66, 66, 89, 0.8)',
          formatter: function (params) {
            var result =
              '<div style="font-size:14px;font-weight:600;margin-bottom:4px">' +
              params[0].axisValue +
              '</div>';
            params.forEach(function (item, index) {
              result +=
                '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' +
                item.color +
                '"></span>';
              result += item.seriesName + '：' + item.data + '<br>';
            });
            return result;
          },
        },
        legend: {
          right: 10,
          data: this.legend,
          icon: 'circle',
        },
        grid: {
          top: 30,
          left: '1%',
          right: '1%',
          bottom: 20,
          containLabel: true,
        },
        color: [
          '#23B899',
          '#387DFF',
          'rgb(250,200,88)',
          'rgb(238,102,102)',
          'rgb(115,192,222)',
          'rgb(252,132,82)',
          'rgb(154,96,180)',
          'rgb(234,124,204)',
        ],
        xAxis: {
          type: 'category',
          boundaryGap: true,
          data: this.timeSource,
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: '#292B3D',
            fontSize: 13,
          },
          axisLine: {
            lineStyle: { color: '#EAEBF0' },
          },
        },
        yAxis: [
          {
            type: 'value',
            // name: '锭速（m/s）',
            axisTick: { show: false },
            axisLine: { show: false },
            axisLabel: {
              show: true,
              fontSize: 13,
              textStyle: {
                color: '#292B3D',
              },
            },
            splitLine: {
              lineStyle: {
                color: '#EAEBF0',
                type: 'dotted',
              },
            },
          },
        ],
        series: this.series,
      };

      return option;
    },
    changeChartTabs() {
      this.series = [];
      this.yAxis.map((devSn, devSnIndex) => {
        devSn.map((item, index) => {
          // 构建seires
          if (index == 0) {
            this.series.push({
              name: '车台' + item.devSn,
              type: 'line',
              symbol: 'circle',
              symbolSize: 8,
              itemStyle: {
                borderWidth: 2,
                borderColor: '#fff',
              },
              data: [],
            });
            this.legend.push('车台' + item.devSn);
          }
          // 如果为llxs需单独处理
          if (this.chartActive == 'llxs') {
            let llxsVal = parseInt(item[this.chartActive]) / 100;
            this.series[devSnIndex]['data'].push(llxsVal);
          } else {
            this.series[devSnIndex]['data'].push(item[this.chartActive]);
          }
        });
      });
      let options = this.setOptions();
      this.chartInit(options);
    },
    async changeGX(val) {
      this.getParams(val);
      this.search.devSn = [];
      if (val) {
        const res = await getSysDictByName(val + '设备');
        if (res.code == 1) {
          let bh = res.data.dataList[0]['bh'];
          this.getEquip(bh);
        }
      } else {
        this.equipOption = [];
      }
    },
    getHeight() {
      this.tableHeight = this.$refs.chartTable.offsetHeight;
    },
    handleSizeChange(val) {
      this.search.current = 1;
      this.search.size = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.search.current = val;
      this.getTableData();
    },
    searchNow() {
      this.$refs['search'].validate((valid, object) => {
        if (valid) {
          // 获取动态的列表表头
          let checked = this.$refs.cascader.getCheckedNodes(true);
          this.chartBtnArr = [];
          let columns = [];
          checked.map((item) => {
            if (item.level == 2) {
              this.chartBtnArr.push({ label: item.label, value: item.value });
              let findindex = null;
              let find = columns.find((param, index) => {
                if (param.label == item.parent.value) {
                  findindex = index;
                  return param.label == item.parent.value;
                }
              });
              if (!find) {
                let data = {
                  label: item.parent.value,
                  children: [
                    {
                      label: item.label,
                      value: item.value,
                    },
                  ],
                };
                columns.push(data);
              } else {
                columns[findindex]['children'].push({
                  label: item.label,
                  value: item.value,
                });
              }
            } else {
              columns.push({
                label: item.label,
                value: item.value,
              });
            }
          });
          this.columns = columns;

          this.getChartData();
          this.getTableData();
        } else {
          this.$message({
            message: '请选择工序、参数类型、机台和时间！',
            iconClass: 'el-icon-warning',
            customClass: 'common-message',
          });
          return false;
        }
      });
    },
    groupBy(array, f) {
      let groups = {};
      array.forEach(function (o) {
        var group = JSON.stringify(f(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
      });
      return Object.keys(groups).map(function (group) {
        return groups[group];
      });
    },
    arrayGroupBy(list, groupId) {
      let sorted = this.groupBy(list, function (item) {
        return [item[groupId]];
      });
      return sorted;
    },
    llxsFilter(row, col, val) {
      return parseInt(val) / 100;
    },
  },
};
</script>

<style lang="stylus" scoped>
.common-wrapper {
  height: 100%;
}

.chart {
  width: 100%;
  height: calc((100% - 134px) * 0.64);
  position: relative;
}

.chart-tabs {
  height: 24px;
}

.chart-table {
  height: calc((100% - 134px) * 0.36);
}

.common-search {
  display: flex;

  ::v-deep .btn-list .el-form-item__content {
    display: flex;
  }
}

::v-deep.chart-radio.el-radio--samll.is-bordered {
  height: 24px;
  line-height: 24px;
  padding: 0 6px;
  border: none;
  margin: 0 10px 0 0;
  background: #EBEBEB;
  z-index: 999;

  .el-radio__input {
    display: none;
  }

  .el-radio__label {
    padding: 0;
    font-size: 14px;
    color: #797979;
  }

  &.is-checked {
    background: #387DFF;
    border-color: #fff;

    .el-radio__label {
      color: #fff;
    }
  }

  & +.el-radio.is-bordered {
    margin: 0 0 0 10px;
  }
}
</style>
<style lang="scss" scoped>
.chart-table {
  ::v-deep.el-table {
    font-size: 13px;
    th {
      background-color: #f8f9fb !important;
      color: #292b3d;
      font-weight: 500;
      padding: 9px 0;
    }
    .el-table__cell {
      padding: 10px 0;
    }
  }
}
</style>
